<template>
  <div class="cateContent">
    <!-- //搜索层 -->
    <div class="search-box">
      <el-form ref="form" :inline="true" size="small">
        <el-form-item>
          <el-input
            v-model="paramsquery.username"
            placeholder="管理员账号"
            style="width: 205px"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="paramsquery.email"
            placeholder="管理员邮箱"
            style="width: 205px"
          />
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="paramsquery.status"
            placeholder="显示状态"
            style="width: 205px"
          >
            <el-option :label="'显示'" :value="1" />
            <el-option :label="'隐藏'" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            plain
            size="small"
            @click="searchCatename"
          >搜索</el-button>
          <el-button
            plain
            @click="resetCate"
          >重置</el-button>
        </el-form-item>
        <el-form-item class="absolut">
          <el-button
            type="primary"
            plain
            size="small"
            style="width: 95px"
            @click="TheAdd"
          >创建用户</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- //表格层 -->
    <div>
      <el-table
        :data="userList"
        border
        style="width: 100%"
      >
        <!-- header-cell-style="text-align:center"  -->
        <el-table-column prop="id" type="id" label="管理员ID" width="90" align="center" />
        <el-table-column prop="username" label="管理员姓名" width="120" align="center" />
        <el-table-column prop="phone" label="手机号" width="130" align="center" />
        <el-table-column prop="email" label="管理员邮箱" align="center" />
        <el-table-column prop="id" label="管理员头像" align="center">
          <template #default="{row}">
            <img
              v-if="row.avatar"
              style="width:40px;height:40px;border-radius: 50%;"
              :src="'http://124.223.14.236:7005/' + row.avatar"
              alt=""
            >
            <img
              v-else
              style="width:40px;height:40px"
              src="	"
              alt=""
            >
          </template>
        </el-table-column>
        <el-table-column prop="role_name_str" label="管理员角色" align="center">
          <template #default="{row}">
            <el-tag type="success">{{ row.role_name_str }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="添加时间" align="center" />
        <el-table-column prop="status" label="状态" align="center">
          <template #default="{row}">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="2"
              @change="changeswitch(row.status,row.id)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="date" label="操作" width="150" class="textcenter" align="center">
          <template #default="{row}">
            <el-row type="flex" justify="center">
              <el-button type="primary" icon="el-icon-edit" circle size="mini" @click="TheEdit(row.id)" />
              <el-button type="danger" icon="el-icon-delete" circle size="mini" @click="TheDel(row.id)" />
            </el-row>
          </template>

        </el-table-column>
      </el-table>
    </div>
    <!-- //添加层 dialog弹出层 -->
    <div>
      <el-dialog :title="title" :visible.sync="dialogFormVisible" width="750px" @close="close">
        <el-form ref="refform" :model="theform" :rules="rules" class="formpad" label-width="120px">
          <el-row type="flex" class="row-bg">
            <el-col :span="10">
              <el-form-item label="管理员名称" prop="username">
                <el-input
                  v-model="theform.username"
                  autocomplete="off"
                  style="width: 215px"
                  placeholder="请输入管理员名称"
                />
              </el-form-item>
            </el-col>
            <el-col :span="10" :offset="2">
              <el-form-item label="管理员邮箱" prop="email">
                <el-input
                  v-model="theform.email"
                  autocomplete="off"
                  style="width: 215px"
                  placeholder="请输入管理员邮箱"
                />
              </el-form-item>
            </el-col>

          </el-row>
          <el-row type="flex" class="row-bg">
            <el-col :span="10">
              <el-form-item label="管理员密码" prop="password" :rules="flag ? rules.password : []">
                <el-input
                  v-model="theform.password"
                  autocomplete="off"
                  style="width: 215px"
                  placeholder="请输入管理员密码"
                />
              </el-form-item>
            </el-col>
            <el-col :span="10" :offset="2">
              <el-form-item label="管理员手机号" prop="phone">
                <el-input
                  v-model="theform.phone"
                  autocomplete="off"
                  style="width: 215px"
                  placeholder="请输入管理员手机号"
                />
              </el-form-item>
            </el-col>

          </el-row>
          <el-row type="flex" class="row-bg">
            <el-col :span="10">
              <el-form-item label="管理员状态" prop="status">
                <el-switch
                  v-model="theform.status"
                  active-text="禁用"
                  inactive-text="开启"
                  :active-value="1"
                  :inactive-value="2"
                />
              </el-form-item>
            </el-col>
            <el-col :span="10" :offset="2">
              <!-- //--------------------------------------------------------------------------------------------------->
              <!-- //文件上传 -->
              <el-form-item label="管理员头像" prop="avatar">
                <div class="footerBtn">
                  <el-button
                    class="el-icon-upload pison"
                    type="success"
                    @click="dialogVisible=true"
                  >上传头像</el-button>

                  <div class="show-preview">
                    <div :style="previews.div" class="preview">
                      <img :src="previews.url" :style="previews.img" width="100%">
                    </div>
                  </div>

                  <!-- 弹出层-裁剪 -->
                  <el-dialog
                    title="编辑头像"
                    :visible.sync="dialogVisible"
                  >
                    <span>
                      <el-row>
                        <input
                          id="uploads"
                          ref="filElem"
                          type="file"
                          accept="image/png, image/jpeg, image/gif, image/jpg"
                          class="el-button hide"
                          style="margin-bottom:15px;display:none"
                          @change="uploadImg($event,1)"
                        >
                        <!-- <el-button class="upload-img" type="primary" plain @click="clickUpload">上传/更换 图片</el-button> -->
                        <!-- <div class="upload-img" @click="clickUpload">点击上传/更换 图片</div> -->
                      </el-row>
                      <el-row>
                        <el-col :span="14">
                          <!-- 裁剪 -->
                          <vueCropper
                            ref="cropper"
                            style="width:100%;height:300px"
                            :img="attach.customaryUrl"
                            :auto-crop="options.autoCrop"
                            :fixed-box="options.fixedBox"
                            :can-move-box="options.canMoveBox"
                            :auto-crop-width="options.autoCropWidth"
                            :auto-crop-height="options.autoCropHeight"
                            :center-box="options.centerBox"
                            @realTime="realTime"
                          />
                        </el-col>
                        <el-col :span="6.5">
                          <h2 align="center" class=" mar-left-50">头像预览</h2>
                          <div class="show-preview">
                            <div :style="previews.div" class="preview">
                              <img :src="previews.url" :style="previews.img" width="100%">
                            </div>
                          </div>
                        </el-col>
                      </el-row>
                      <el-button type="primary" plain @click="clickUpload">上传图片</el-button>
                      <el-row class="footerBtn" align="center">

                        <el-button type="primary " size="medium" round @click="confirm('blob')">确认</el-button>
                        <el-button type="info" size="medium" round @click="handleClose">取消</el-button>
                      </el-row>
                    </span>
                  </el-dialog>
                </div>
                <!-- ————————————————
            版权声明：本文为CSDN博主「前端菜鸟-张晓震」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
            原文链接：https://blog.csdn.net/qq_42074281/article/details/105112968 -->
                <!-- //--------------------------------------------------------------------------------------------------->
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="管理员角色" prop="roleid_list">
            <el-checkbox-group v-model="theform.roleid_list">
              <el-checkbox
                v-for="item in checkList"
                :key="item.id"
                :label="item.id"
                :value="item.id"
              >{{ item.role_name }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="close">取 消</el-button>
          <el-button
            type="primary"
            @click="thesubmit"
          >确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- //分页器 -->
    <el-row type="flex" justify="end">
      <el-pagination
        :current-page="paramsquery.page"
        :page-sizes="[2, 5, 10, 15]"
        :page-size="paramsquery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-row>
  </div>
</template>
<script>
import { GetuserList, GetroleList, AddroleList, imgroleList, GetroleId, PutroleId, DelroleId, Changerole } from '@/api/permission/user'

export default {
  data() {
    return {
      // 多选框组
      arr: [],
      thecheck: [],
      checkList: [],
      dirnameList: [],
      total: 1,
      // 表格
      userList: [],
      // 搜索层
      val1: '显示',
      val2: '隐藏',
      // 弹出层Form
      theform: {
        avatar: '',
        email: '',
        password: '',
        phone: '',
        status: 2,
        username: '',
        roleid_list: []
      },
      dialogFormVisible: false,
      title: '添加学科',
      // 校验
      rules: {

        email: [
          { required: true, message: '必须填写', trigger: 'blur' },
          { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '必须是正式邮箱格式嗷！', trigger: 'blur' }
        ],

        phone: [
          { required: true, message: '必须填写', trigger: 'blur' },
          { pattern: /^1[3|4|5|6|7|8|9]\d{9}/, message: '必须是手机号码格式嗷！', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '必须填写', trigger: 'blur' }
        ],
        roleid_list: [
          { required: true, message: '必须填写', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '初次创建必填嗷！', trigger: 'blur' }
        ]
      },
      flag: false,
      // 渲染/分页器
      paramsquery: {
        username: '',
        status: '',
        email: '',
        page: 1,
        limit: 10

      },
      // 文件上传----------------------------------------------------------------------------------------------
      dialogVisible: false,
      options: {
        autoCrop: true, // 默认生成截图框
        fixedBox: true, // 固定截图框大小
        canMoveBox: false, // 截图框不能拖动
        centerBox: false, // 截图框被限制在图片里面
        autoCropWidth: 220, // 截图框宽度
        autoCropHeight: 220 // 截图框高度
      },
      previews: {}, // 实时预览图数据
      attach: {
        // 后端附件表
        id: '',
        userId: '',
        customaryUrl: '', // 原图片路径
        laterUrl: '', // 裁剪后图片路径  /static/logo.png
        attachType: 'photo' // 附件类型
      },
      // 文件上传----------------------------------------------------------------------------------------------
      rolearr: []
    }
  },
  created() {
    this.initGetuserList()
    this.initroleList()
  },
  methods: {
    // 点击switch按钮切换状态 并上传
    async changeswitch(isshow, id) {
      // console.log(222)
      await Changerole({
        ...this.theformm,
        id: id,
        status: isshow
      })
      this.$message.success('修改按钮权限成功')
      this.initGetuserList()
    },
    // 点击编辑
    async TheEdit(id) {
      this.flag = false
      const res = await GetroleId(id)
      console.log(res)
      // 赋值给表单
      this.theform = res
      this.previews = { url: 'http://124.223.14.236:7005/' + res.avatar }
      const roleid = res.roleid_list
      // // 处理回显分配的角色
      // console.log(roleid, 1, 'therole')
      this.thecheck = roleid
      this.dialogFormVisible = true
    },
    // role 职位
    async initroleList() {
      const res = await GetroleList()
      console.log(res, 'role')
      this.checkList = res.list
    },
    // 点击添加
    TheAdd() {
      this.flag = true
      this.dialogFormVisible = true
    },
    // 点击删除
    async TheDel(id) {
      await DelroleId(id)
      this.$message.success('删除成功')
      this.initGetuserList()
    },
    // 提交 添加/编辑
    thesubmit() {
      this.$refs.refform.validate(async(isOK) => {
        if (isOK) {
          if (this.theform.id) {
            await PutroleId(this.theform)
          } else {
            await AddroleList(this.theform)
          }
          this.initGetuserList()
          this.close()
        }
      })
    },
    // 渲染页面
    async initGetuserList() {
      const res = await GetuserList(this.paramsquery)
      console.log(res)
      this.userList = res.list
      this.total = res.total
    },
    close() {
      this.dialogFormVisible = false
      this.theform = {
        avatar: '',
        email: '',
        password: '',
        phone: '',
        status: '',
        username: '',
        roleid_list: []
      }
      this.thecheck = []
      this.previews = ''
      // this.attach = {
      //   id: '',
      //   userId: '',
      //   customaryUrl: '', // 原图片路径
      //   laterUrl: '', // 裁剪后图片路径  /static/logo.png
      //   attachType: 'photo' // 附件类型
      // }
    },

    // 分页器
    handleSizeChange(val) {
      this.paramsquery.page = 1
      this.paramsquery.limit = val
      this.initGetuserList()
    },
    handleCurrentChange(val) {
      this.paramsquery.page = val
      this.initGetuserList()
    },
    // 文件上传-------------------------------------------------------------------------------------------------------
    // 控制弹出层关闭
    handleClose() {
      this.dialogVisible = false
    },
    // 实时预览
    realTime(data) {
      this.previews = data
    },
    // 点击图片调取input
    clickUpload() {
      this.$refs.filElem.dispatchEvent(new MouseEvent('click'))
    },
    // 选择本地图片
    uploadImg(e, num) {
      var file = e.target.files[0]
      if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
        this.$message.error('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种')
        return false
      }
      // fileReader 接口，用于异步读取文件数据
      var reader = new FileReader()
      reader.readAsDataURL(file) // 重要 以dataURL形式读取文件
      reader.onload = e => {
        // data = window.URL.createObjectURL(new Blob([e.target.result])) 转化为blob格式
        const data = e.target.result
        // console.log(data)
        this.attach.customaryUrl = data
        // 转化为base64
        reader.readAsDataURL(file)
        // 转化为blob
      }
    },

    // 确认截图,上传
    confirm(type) {
      this.$refs.cropper.getCropData(async res => {
        // console.log(res)// 这里截图后的url 是base64格式 让后台转下就可以let base64Src= src;
        this.laterUrl = res
        this.theform.avatar = this.laterUrl
        this.dialogVisible = false
        const res2 = await imgroleList({
          file: this.theform.avatar,
          filename: 'icon.png'
        })
        this.theform.avatar = res2.url
        // console.log(res2)
        console.log(this.theform.avatar)
      })
    },
    // 文件上传----------------------------------------------------------------------------------------------
    // 点击搜索
    searchCatename() {
      this.paramsquery.page = 1
      this.initGetuserList()
    },
    // 重置
    resetCate() {
      this.paramsquery = {
        username: '',
        status: '',
        email: '',
        page: 1,
        limit: 10
      }
      this.initGetuserList()
    },
    thechangeTag(aaa) {
      // console.log(aaa)
      this.arr.push(aaa)
      // console.log(this.arr)

      this.theform.roleid_list = this.arr
      console.log(this.theform.roleid_list)
    }
  }
}
</script>
<style lang="scss" scoped>
.cateContent {

  padding: 18px;
  background-color: #ffffff;
  position: relative;
  .absolut {
    position: absolute;
    top: 15px;
    right: 2px;

  }
  .pison{
    position: absolute;
    top: 45px;
    right: 150px;
  }
// 文件上传----------------------------------------------------------------------------------------------
/* 弹性布局 水平居中 */
.el-dialog{
  width: 500px !important;
  height: auto;
}
.show-preview {
  display: flex;
  justify-content: center;
}
.preview {
  border-radius: 50%;
  overflow: hidden;
  border: 1px solid #c1bcbc;
  background: #ffffff;
  width: 180px !important;
  height: 180px !important;
  margin-left: 40px;
  margin-top: 10px;
}

.upload-img{
  width: 100px;
  height: 30px;
  border:1px solid #f08512;
  margin-bottom: 5px;
  line-height: 30px;
  text-align: center;
  cursor: pointer;
}
.footerBtn {
  display: flex;
  justify-content: center;
  margin-top: 25px;
}

}
</style>

